package viz.plugin.bank.ocr

import androidx.annotation.NonNull

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler

/** BankOcrPlugin */
class BankOcrPlugin: FlutterPlugin, MethodCallHandler, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private var activityBinding: ActivityPluginBinding? = null

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "bank_ocr")
    channel.setMethodCallHandler(this)
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: MethodChannel.Result) {
    when(call.method){
      "getPlatformVersion" -> {
        result.success("Android ${android.os.Build.VERSION.RELEASE}")
      }
      "bankCardOcr" -> {
        val bankOcrDelegate = BankOcrDelegate(activityBinding!!.activity, result, call)
        activityBinding?.addActivityResultListener(bankOcrDelegate)
        bankOcrDelegate.ocr()
      }
      "init"->{
        val bankOcrDelegate = BankOcrDelegate(activityBinding!!.activity, result, call)
        bankOcrDelegate.initOCR()
      }
      "bankOcrFromImagePath"->{
        val bankOcrDelegate = BankOcrDelegate(activityBinding!!.activity, result, call)
        val args = call.arguments as Map<String, Any>
        bankOcrDelegate.bankOcrFromImagePath(args["imagePath"] as String)
      }
      else->{
        result.notImplemented()
      }
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    activityBinding = binding
  }

  override fun onDetachedFromActivityForConfigChanges() {
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
  }

  override fun onDetachedFromActivity() {
    activityBinding = null
  }
}
